package com.freewater.springboot.demo.aop.api.cflow;

import com.freewater.springboot.demo.aop.api.SimpleBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ControlFlowPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        main.test();
    }

    public void test() {
        final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        AccountService accountService = applicationContext.getBean(AccountService.class);
        ControlFlowPointcut pointcut = new ControlFlowPointcut(Main.class, "execute");
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(pointcut, new SimpleBeforeAdvice());
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.addAdvisor(advisor);
        proxyFactory.setTarget(accountService);
        AccountService proxy = (AccountService) proxyFactory.getProxy();
        System.out.println("第一次执行updateBalanceAndExpress 开始------------------------");
        proxy.updateBalanceAndExpress(); // 没有在execute方法中调用accountService的方法，所以不会被advice
        System.out.println("第一次执行updateBalanceAndExpress 结束------------------------");
        System.out.println("\n" + "第二次执行updateBalanceAndExpress 开始------------------------");
        execute(proxy); // 在execute方法中调用accountService的方法，所以我会被advice
        System.out.println("第二次执行updateBalanceAndExpress 结束------------------------");
    }

    public void execute(AccountService accountService) {
        accountService.updateBalanceAndExpress();
    }
}
